package com.kinptm.masterclock.service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.kinptm.masterclock.Intents;
import com.kinptm.masterclock.MasterClockApplication;
import com.kinptm.masterclock.R;
import com.kinptm.masterclock.utils.Ln;

/**
 * Created by pc on 13-11-26.
 */
public class KeepRunningService extends Service {
    private static final int SERVICE_ID = 0xf0;
    private static final int NOTIFICATION_ID = 0xf1;

    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        String SCREEN_OFF_ACTION 广播：屏幕被关闭。 "android.intent.action.SCREEN_OFF"
//        String SCREEN_ON_ACTION 广播：屏幕已经被打开。 "android.intent.action.SCREEN_ON"

//        Notification notification = new NotificationCompat.Builder(this).
//                setContentTitle("MasterClock").
//                setContentText("为避免闹铃失效,请勿结束该进程!").
//                setSmallIcon(R.drawable.ic_launcher).
//                setTicker(String.format("目前有%s个闹铃", 1)).
//                setAutoCancel(false).
//                setOngoing(false).
//                setPriority(Notification.PRIORITY_HIGH).
//                setContentIntent(PendingIntent.getActivity(this, 2, new Intent(Intent.ACTION_VIEW), 0)).
//                build();

        startForeground(NOTIFICATION_ID, new Notification());

        if (intent != null && intent.hasExtra(Intents.ALARM.EXTRA_ALARM_ACTION) &&
                intent.hasExtra(Intents.ALARM.EXTRA_ALARM_ID) &&
                intent.hasExtra(Intents.ALARM.EXTRA_ALARM_TIME)) {
            String action = intent.getStringExtra(Intents.ALARM.EXTRA_ALARM_ACTION);
            int id = intent.getIntExtra(Intents.ALARM.EXTRA_ALARM_ID, 0);
            long millis = intent.getLongExtra(Intents.ALARM.EXTRA_ALARM_TIME, 0);

            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent alarmIntent = new Intent(action);
            alarmIntent.putExtra(Intents.ALARM.EXTRA_ALARM_ID, id);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, alarmIntent, 0);
            alarmManager.set(AlarmManager.RTC_WAKEUP, millis, pendingIntent);
            Ln.d("KeepRunningService action=%s , id=%s , millls=%s ", action, id, millis);
            Ln.d("KeepRunningService 设置闹钟成功!");
        } else {
            Ln.e("KeepRunningService  Intent = null !");
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Ln.d("KeepRunningService destory , restart !");
        Intent intent = new Intent(Intents.ALARM.ACTION_ALARM_SERVICE);
        startService(intent);
    }
}
